package com.learn.security.handler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.learn.result.ResultUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String result  = "";
        if(authException instanceof BadCredentialsException){
            result = JSON.toJSONString(
                ResultUtils.error(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage())
            );
        }else if(authException instanceof InternalAuthenticationServiceException){
            result = JSON.toJSONString(
                ResultUtils.error(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage())
            );
        }else{
            result = JSON.toJSONString(
                ResultUtils.error(HttpServletResponse.SC_UNAUTHORIZED,"匿名用户无访问权限，请登录后访问")
            );
        }
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }

}